package com.app.xutils;

import com.app.config.AppHttpKey;
import com.app.config.ApplicationConfig;
import com.app.utils.CommonUtil;
import com.app.utils.FileImageUtils;
import com.app.utils.JSONTool;
import com.app.utils.SharePrefUtil;
import com.app.utils.SystemPrintl;

import org.xutils.DbManager;
import org.xutils.common.Callback;
import org.xutils.common.util.KeyValue;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.io.File;
import java.util.List;
import java.util.Map;

/**
 * 作者：lblbh on 2016/12/5 15:10
 * 邮箱：lanbuhan@163.com
 * 功能：全局工具类
 */
public class Xutils {


    /**
     * 发送get请求
     * @param <T>
     */
    public static <T> Callback.Cancelable Get(String url, Map<String,String> map, Callback.CommonCallback<T> callback){
        RequestParams params=new RequestParams(url);
        params.setCacheMaxAge(0);
        params = addHeadToken(params);
        List<KeyValue> stringParams = params.getStringParams();
        for (KeyValue key:
             stringParams) {
            SystemPrintl.systemPrintl("key-->"+key.key+"<---value--->"+key.value);
        }
        if(null!=map){
            for(Map.Entry<String, String> entry : map.entrySet()){
                params.addQueryStringParameter(entry.getKey(), entry.getValue());
                SystemPrintl.systemPrintl("key-->"+entry.getKey()+"<---value--->"+entry.getValue());
            }
        }
        Callback.Cancelable cancelable = x.http().get(params, callback);
        return cancelable;
    }

    /**
     * 发送地图使用请求
     * @param <T>
     */
    public static <T> Callback.Cancelable GetMap(String url, Map<String,String> map, Callback.CommonCallback<T> callback){
        RequestParams params=new RequestParams(url);
        params.setCacheMaxAge(0);
        params = addHeadTokenAndCity(params);
        if(null!=map){
            for(Map.Entry<String, String> entry : map.entrySet()){
                params.addQueryStringParameter(entry.getKey(), entry.getValue());

                SystemPrintl.systemPrintl("key-->"+entry.getKey()+"<---value--->"+entry.getValue());
            }
        }
        Callback.Cancelable cancelable = x.http().get(params, callback);
        return cancelable;
    }


    /**
     * 发送post请求
     * @param <T>
     */
    public static <T> Callback.Cancelable Post(String url, Map<String,String> map, Callback.CommonCallback<T> callback){
        RequestParams params=new RequestParams(url);
        params.setCacheMaxAge(0);
        params = addHeadToken(params);
        if(null!=map){
            for(Map.Entry<String, String> entry : map.entrySet()){
                params.addParameter(entry.getKey(), entry.getValue());
                SystemPrintl.systemPrintl("key-->"+entry.getKey()+",value-->"+entry.getValue());
            }
        }
        Callback.Cancelable cancelable = x.http().post(params, callback);
        return cancelable;
    }


    /**
     * 上传文件
     * @param <T>
     */
    public static <T> Callback.Cancelable UpLoadImg(String url, Map<String,String> map, String filePath, Callback.CommonCallback<T> callback){
        RequestParams params=new RequestParams(url);
        if(null!=map){
            for(Map.Entry<String, String> entry : map.entrySet()){
                params.addParameter(entry.getKey(), entry.getValue());
            }
        }


        if(CommonUtil.isRequestStr(filePath)){
            String string = filePath.toString();
            String replace = string.replace("file://", "");
            File file = new File(replace);
            params.addBodyParameter("filestream",file,"application/octet-stream");
        }
        params.setMultipart(true);
        Callback.Cancelable cancelable = x.http().post(params, callback);
        return cancelable;
    }

    /**
     * 上传文件 多张图片
     * @param <T>
     */
    public static <T> Callback.Cancelable UpLoadImgs(String url, Map<String,String> map, List<String> filePaths, Callback.CommonCallback<T> callback){
        RequestParams params=new RequestParams(url);
        params = addHeadToken(params);
        if(null!=map){
            for(Map.Entry<String, String> entry : map.entrySet()){
                params.addParameter(entry.getKey(), entry.getValue());
                SystemPrintl.systemPrintl("key---->"+entry.getKey()+",entry.getValue()"+entry.getValue());
            }
        }

        File filesd = new File(CommonUtil.getSDPath()+ File.separator + ApplicationConfig.SD_FIEL_NAME);
        if(!filesd.exists()){
            filesd.mkdirs();
        }

        if(CommonUtil.isRequestList(filePaths)){
            for (int i=0,j=filePaths.size();i<j;i++){
                String string = filePaths.get(i).toString();
                String replace = string.replace("file://", "");
                ///storage/emulated/0/DCIM/P70506-105024.jpg
                ///storage/emulated/0/Pictures/Screenshots/S70527-105527.jpg
//                /storage/emulated/0/Pictures/Screenshots/S70527-105527.jpg
//                File file = new File(replace);

                String path = filesd.getPath();
                String imgStr = FileImageUtils.compressImage(replace,path+"/"+i+".jpg",30);

                params.addBodyParameter("file_data",new File(imgStr),"application/octet-stream");
            }
//

//            params.addBodyParameter();
        }
        params.setMultipart(true);
        Callback.Cancelable cancelable = x.http().post(params, callback);
        return cancelable;
    }

    /**
     * 上传文件
     * @param <T>
     */
    public static <T> Callback.Cancelable UpLoadFile(String url, Map<String,Object> map, Callback.CommonCallback<T> callback){
        RequestParams params=new RequestParams(url);
        if(null!=map){
            for(Map.Entry<String, Object> entry : map.entrySet()){
                params.addParameter(entry.getKey(), entry.getValue());
            }
        }
        params.setMultipart(true);
        Callback.Cancelable cancelable = x.http().post(params, callback);
        return cancelable;
    }

    /**
     * 下载文件
     * @param <T>
     */
    public static <T> Callback.Cancelable DownLoadFile(String url, String filepath, Callback.CommonCallback<T> callback){
        RequestParams params=new RequestParams(url);
        //设置断点续传
        params.setAutoResume(true);
        params.setSaveFilePath(filepath);
        Callback.Cancelable cancelable = x.http().get(params, callback);
        return cancelable;
    }

    /**
     *   设置数据库 config  DB_DATA
     */
    static DbManager.DaoConfig daoConfig;
    public static DbManager.DaoConfig getDaoConfig(){
//        File file=new_icon File(CommonUtil.DB_DATA);
        if(daoConfig==null){
            daoConfig=new DbManager.DaoConfig()
//                    .setDbDir(file)
                    .setDbName(ApplicationConfig.DB_NAME)
                    .setDbVersion(ApplicationConfig.DB_VERSION)
                    .setAllowTransaction(true)
                    .setDbUpgradeListener(new DbManager.DbUpgradeListener() {
                        @Override
                        public void onUpgrade(DbManager db, int oldVersion, int newVersion) {

                            //处理数据库升级工作

                        }
                    }).setDbOpenListener(new DbManager.DbOpenListener() {
                        @Override
                        public void onDbOpened(DbManager db) {
                            db.getDatabase().enableWriteAheadLogging();
                        }
                    });
        }

        return daoConfig;
    }


    /**
     * 添加请求头 用户信息传递
     * @param params
     * @return
     */
    private static RequestParams addHeadToken(RequestParams params){
        //SharePrefUtil.saveString(SharePrefUtil.KEY.APP_USER,result);
        addHeadTokenAndCity(params);


//        boolean isCurrentLocal = SharePrefUtil.getBoolean(SharePrefUtil.KEY.CITY_STATE,false);

        String latitude = ""; //纬度
        String lontitude = "";// 经度
//        if(isCurrentLocal){
            //定位成功 使用定位成功为止
            latitude = SharePrefUtil.getString(SharePrefUtil.KEY.LATITUDE,"");
            lontitude = SharePrefUtil.getString(SharePrefUtil.KEY.LONTITUDE,"");
//        }


        if(CommonUtil.isRequestStr(latitude) && CommonUtil.isRequestStr(lontitude)){
            //对非法坐标 进行处理
            if(ApplicationConfig.ERROR_LAT.equals(latitude) || ApplicationConfig.ERROR_LAT.equals(lontitude)){
                latitude = "";
                lontitude = "";
            }
            params.addQueryStringParameter(AppHttpKey.LONGITUDE, lontitude);
            params.addQueryStringParameter(AppHttpKey.LATITUDE, latitude);
        }


        return params;
    }


    /**
     * 添加请求头 token  city
     * @param params
     * @return
     */
    private static RequestParams addHeadTokenAndCity(RequestParams params){
        String info = SharePrefUtil.getString(SharePrefUtil.KEY.APP_USER,null);
        if(CommonUtil.isRequestStr(info)){
            String token = JSONTool.requestJSONfindName(info,JSONTool.Enum.ACCESS_TOKEN);
            params.setHeader(AppHttpKey.COOKIE,token);
        }

        //添加城市
        params.addQueryStringParameter(AppHttpKey.SITE_ID, "1");

        String appVersion = CommonUtil.getVersion();
        if(CommonUtil.isRequestStr(appVersion)){
            params.addQueryStringParameter(AppHttpKey.VSERSION, appVersion);
        }

        params.addQueryStringParameter(AppHttpKey.SYSTEM_IDENTIFIER, AppHttpKey.ANDROID);


        return params;
    }
}
